package com.zys.http.processor.spring;

import cn.hutool.core.text.CharSequenceUtil;
import com.intellij.extapi.psi.ASTDelegatePsiElement;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.zys.http.constant.HttpEnum;
import com.zys.http.entity.param.ParamProperty;
import com.zys.http.entity.tree.MethodNodeData;
import com.zys.http.entity.velocity.MethodItem;
import com.zys.http.extension.setting.HttpSetting;
import com.zys.http.processor.AbstractKotlinApiProcessor;
import com.zys.http.tool.UrlTool;
import com.zys.http.tool.VelocityTool;
import com.zys.http.ui.tree.node.MethodNode;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.idea.stubindex.KotlinAnnotationsIndex;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;

import java.util.*;

/**
 * @author zhou ys
 * @since 2024-05-16
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SpringKotlinApiProcessor extends AbstractKotlinApiProcessor {
    public static final SpringKotlinApiProcessor INSTANCE = new SpringKotlinApiProcessor();

    @Override
    @SuppressWarnings("deprecation")
    public List<? extends PsiElement> controllers(Project project, Module module) {
        Optional<GlobalSearchScope> scopeOp = Optional.of(module).map(Module::getModuleScope);

        Collection<KtAnnotationEntry> entries = ApplicationManager.getApplication().runReadAction((Computable<Collection<KtAnnotationEntry>>) () -> {
            Collection<KtAnnotationEntry> all = new ArrayList<>();
            for (SpringEnums.Controller controller : SpringEnums.Controller.values()) {
                if (controller.equals(SpringEnums.Controller.RESPONSE_BODY)) {
                    continue;
                }
                String shortClassName = controller.getShortClassName();
                all.addAll(scopeOp.map(ms -> KotlinAnnotationsIndex.getInstance().get(shortClassName, project, ms)).orElse(new ArrayList<>()));
            }

            String customAnno = HttpSetting.getInstance().getCustomAnno();
            if (CharSequenceUtil.isNotEmpty(customAnno) && !customAnno.endsWith(".")) {
                String shortName = customAnno.substring(customAnno.lastIndexOf('.') + 1);
                all.addAll(scopeOp.map(ms -> KotlinAnnotationsIndex.getInstance().get(shortName, project, ms)).orElse(new ArrayList<>()));
            }
            return all;
        });

        return entries.stream()
                .map(PsiElement::getParent)
                .map(KtDeclarationModifierList.class::cast)
                .map(KtDeclarationModifierList::getParent)
                .filter(KtClass.class::isInstance)
                .map(KtClass.class::cast)
                .toList();
    }

    @Override
    public String controllerPath(PsiElement psiElement) {
        if (!(psiElement instanceof KtClass ktClass)) {
            return "";
        }
        KtModifierList modifierList = ktClass.getModifierList();
        if (Objects.isNull(modifierList)) {
            return "";
        }
        // 确保有引用 RequestMapping, 找不到解析引用的方法, 先这样吧
        List<KtImportDirective> imports = ktClass.getContainingKtFile().getImportDirectives();
        boolean hasRequest = imports.stream().map(ASTDelegatePsiElement::getText).anyMatch(text ->
                text.equals("import " + SpringEnums.Method.REQUEST.getClazz()) || "import org.springframework.web.bind.annotation.*".equals(text)
        );
        if (!hasRequest) {
            return "";
        }
        List<KtAnnotationEntry> entries = modifierList.getAnnotationEntries();
        for (KtAnnotationEntry entry : entries) {
            Name shortName = entry.getShortName();
            if (Objects.isNull(shortName)) {
                continue;
            }
            String shorName = entry.getShortName().toString();
            if (SpringEnums.Method.REQUEST.getClazz().endsWith(shorName)) {
                return annotationValue(entry, new String[]{VALUE_KEY, "path"});
            }
        }

        return "";
    }

    @Override
    public String methodPath(PsiElement element) {
        if (!(element instanceof KtNamedFunction function)) {
            return null;
        }
        List<KtAnnotationEntry> entries = function.getAnnotationEntries();
        for (KtAnnotationEntry o : entries) {
            Name shortName = o.getShortName();
            if (Objects.isNull(shortName)){
                continue;
            }
            if (SpringEnums.Method.contains(shortName.asString())) {
                return annotationValue(o, new String[]{VALUE_KEY, "path"});
            }
            if (SpringEnums.Method.contains("org.springframework.web.bind.annotation." + shortName.asString())) {
                return annotationValue(o, new String[]{VALUE_KEY, "path"});
            }
        }
        return null;
    }

    @Override
    protected @Nullable MethodNode createMethodNode(@NotNull KtNamedFunction function, String controllerPath, String contextPath) {
        // 过滤某个符合的要求的注解
        KtModifierList modifierList = function.getModifierList();
        if (Objects.isNull(modifierList)) {
            return null;
        }
        String path = "";
        HttpEnum.HttpMethod httpMethod = null;
        List<KtAnnotationEntry> entries = function.getAnnotationEntries();
        for (KtAnnotationEntry o : entries) {
            httpMethod = SpringEnums.Method.get(Objects.requireNonNull(o.getShortName()).asString());
            if (Objects.isNull(httpMethod)) {
                httpMethod = SpringEnums.Method.get("org.springframework.web.bind.annotation." + Objects.requireNonNull(o.getShortName()).asString());
                if (HttpEnum.HttpMethod.REQUEST.equals(httpMethod)) {
                    httpMethod = HttpEnum.HttpMethod.requestMappingConvert(o);
                }
            }
            if (Objects.nonNull(httpMethod)) {
                path = annotationValue(o, new String[]{VALUE_KEY, "path"});
                break;
            }
        }
        if (Objects.isNull(path) || Objects.isNull(httpMethod)) {
            return null;
        }

        MethodNodeData data = new MethodNodeData(httpMethod, path, controllerPath, contextPath);
        data.setPsiElement(function);
        data.setDescription(methodSwagger(function));
        return new MethodNode(data);
    }

    @Override
    protected void parameterParse(@NotNull KtParameter parameter, @NotNull Map<String, ParamProperty> map, boolean isJsonPretty) {
        String parameterName = parameter.getName();
        List<KtAnnotationEntry> entries = parameter.getAnnotationEntries().stream().filter(entry -> Objects.nonNull(entry.getShortName())).toList();
        String[] keys = new String[]{VALUE_KEY, NAME_KEY};

        KtAnnotationEntry headerAnno = entries.stream().filter(entry ->
                SpringEnums.Param.REQUEST_HEADER.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                SpringEnums.Param.REQUEST_HEADER.getShortName().equals(entry.getShortName().asString())
        ).findFirst().orElse(null);

        if (Objects.nonNull(headerAnno)) {
            ParamProperty property = map.getOrDefault(REQUEST_TYPE_KEY, null);
            if (property == null) {
                map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            }
            map.put(parameterName, new ParamProperty("", HttpEnum.ParamUsage.HEADER));
            return;
        }

        // 参数
        KtAnnotationEntry paramAnno = entries.stream().filter(entry ->
                SpringEnums.Param.REQUEST_PARAM.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                SpringEnums.Param.REQUEST_PARAM.getShortName().equals(entry.getShortName().asString())
        ).findFirst().orElse(null);
        HttpEnum.ParamUsage paramUsage = HttpEnum.ParamUsage.URL;
        if (Objects.nonNull(paramAnno)) {
            String annotationValue = annotationValue(paramAnno, keys);
            if (CharSequenceUtil.isNotEmpty(annotationValue)) {
                parameterName = annotationValue;
            }
        }

        String canonicalText = Objects.requireNonNull(parameter.getTypeReference()).getText();
        if (canonicalText.contains("org.springframework.web.multipart.MultipartFile") || "MultipartFile".equals(canonicalText)) {
            // 说明是文件
            KtAnnotationEntry partAnno = entries.stream().filter(entry ->
                    SpringEnums.Param.REQUEST_PART.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                    SpringEnums.Param.REQUEST_PART.getShortName().equals(entry.getShortName().asString())
            ).findFirst().orElse(null);
            if (Objects.nonNull(partAnno)) {
                // @RequestPart 是否有 value 或 name 属性, 如果有会将请求参数名变为那个
                String annotationValue = annotationValue(partAnno, keys);
                if (CharSequenceUtil.isNotEmpty(annotationValue)) {
                    parameterName = annotationValue;
                }
            }

            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.MULTIPART_FORM_DATA, HttpEnum.ParamUsage.HEADER));
            map.put(parameterName, new ParamProperty("", HttpEnum.ParamUsage.FILE));
            return;
        }

        KtAnnotationEntry pathAnno = entries.stream().filter(entry ->
                SpringEnums.Param.PATH_VARIABLE.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                SpringEnums.Param.PATH_VARIABLE.getShortName().equals(entry.getShortName().asString())
        ).findFirst().orElse(null);
        if (Objects.nonNull(pathAnno)) {
            paramUsage = HttpEnum.ParamUsage.PATH;
            String annotationValue = annotationValue(pathAnno, keys);
            if (CharSequenceUtil.isNotEmpty(annotationValue)) {
                parameterName = annotationValue;
            }
        }

        Object paramDefaultTypeValue = typeDefaultValue(parameter.getProject(), parameter);
        if (Objects.isNull(paramDefaultTypeValue)) {
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            return;
        }
        boolean isJson = entries.stream().anyMatch(entry ->
                SpringEnums.Param.REQUEST_BODY.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                SpringEnums.Param.REQUEST_BODY.getShortName().equals(entry.getShortName().asString())
        );

        parameterParseResult(parameterName, paramDefaultTypeValue, isJson, isJsonPretty, map, paramUsage);
    }

    @Override
    protected MethodItem postmanMethodItem(KtNamedFunction function, String contextPath, String controllerPath) {
        KtModifierList modifierList = function.getModifierList();
        if (Objects.isNull(modifierList)) {
            return null;
        }
        List<KtAnnotationEntry> entries = function.getAnnotationEntries();
        MethodItem item = new MethodItem();
        // 方法名
        String methodSwagger = methodSwagger(function);
        methodSwagger = CharSequenceUtil.isEmpty(methodSwagger) ? function.getName() : methodSwagger;
        item.setName(methodSwagger);

        // 请求方式、请求uri、请求头类型
        String path;
        HttpEnum.HttpMethod httpMethod;
        for (KtAnnotationEntry entry : entries) {
            httpMethod = SpringEnums.Method.get(Objects.requireNonNull(entry.getShortName()).asString());
            if (Objects.isNull(httpMethod)) {
                httpMethod = SpringEnums.Method.get("org.springframework.web.bind.annotation." + Objects.requireNonNull(entry.getShortName()).asString());
                if (HttpEnum.HttpMethod.REQUEST.equals(httpMethod)) {
                    httpMethod = HttpEnum.HttpMethod.requestMappingConvert(entry);
                }
            }
            if (Objects.isNull(httpMethod)) {
                continue;
            }

            item.setMethod(httpMethod.name());

            // 请求 uri
            path = annotationValue(entry, new String[]{VALUE_KEY, "path"});
            item.setUri(UrlTool.buildMethodUri(contextPath, controllerPath, path));

            // 请求参数类型
            VelocityTool.buildParamProperty(function, item);
            return item;
        }

        return null;
    }
}
